#coding:utf-8
#import necessary package
import socket
import time
import sys
import RPi.GPIO as GPIO
import Adafruit_PCA9685#导入Adafruit_PCA9685模块
import json
pwm = Adafruit_PCA9685.PCA9685()
#define host ip: Rpi's IP
HOST_IP = "192.168.1.12"
HOST_PORT = 8888
print("Starting socket: TCP...")
#1.create socket object:socket=socket.socket(family,type)
socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("TCP server listen @ %s:%d!" %(HOST_IP, HOST_PORT) )
host_addr = (HOST_IP, HOST_PORT)
#2.bind socket to addr:socket.bind(address)
socket_tcp.bind(host_addr)
#3.listen connection request:socket.listen(backlog)
socket_tcp.listen(1)
#4.waite for client:connection,address=socket.accept()
socket_con, (client_ip, client_port) = socket_tcp.accept()
print("Connection accepted from %s." %client_ip)
socket_con.send("Welcome to RPi TCP server!".encode())
def set_servo_angle(channel, angle):#输入角度转换成12^精度的数值
    date=int(4096*((angle*11)+500)/20000)#进行四舍五入运算 date=int(4096*((angle*11)+500)/(20000)+0.5)
    pwm.set_pwm(channel,0, date)
    pwm.set_pwm_freq(50)
def set_init(a_angle,b_angle):
    set_servo_angle(3, a_angle)
    set_servo_angle(2, b_angle)
    time.sleep(0.001)
#@ print("hallow")



###主循环
while True:
    try:
        data=socket_con.recv(512)
        if len(data)>0:
            #str.encode(data)
            
            data=bytes.decode(data)
            print("Received:%s"%data)
            data=str(data)
            list = json.loads(data)
            #print(list.size())
            print(list)
            set_init(int(list[0]),int(list[1]))
            socket_con.send(data.encode('utf-8'))
            #time.sleep(0.01)
            continue
    except Exception:
        socket_tcp.close()
        sys.exit(1)
